import router from './router'
import store from './store'
import i18n from './lang'
import NProgress from 'nprogress'
import { getCookie } from '@/utils/cache'
import * as api from '@/api/index'
import en from 'element-plus/es/locale/lang/en';
import zhCn from 'element-plus/es/locale/lang/zh-cn';
import localEn from '@/lang/en.js'
import localZh from '@/lang/zh.js'
import versionTood from "@/libs/versionUpdate";

// 开发环境才加载样式，避免生产环境打包进去
if (import.meta.env.VITE_USER_NODE_ENV === 'development') {
  import('nprogress/nprogress.css')
}

const whiteList = ['/login', '/reg', '/callSign', '/queryDetails']

const setLocale = (data) => {
  return new Promise((resolve) => {
    i18n.global.setLocaleMessage('zh', { ...data.zh, ...zhCn, ...localZh.person });
    i18n.global.setLocaleMessage('en', { ...data.en, ...en, ...localEn.person });
    resolve();
  });
};


router.beforeEach(async (to, from, next) => {
  NProgress.start()
  const langList = store.getters.langList;
  const token = getCookie(import.meta.env.VITE_VUETOKEN_STR)
  if (!langList.zh) {
    setLocale({ en: en, zh: zhCn });
    // api.default.user.getLang().then(res => {
    //   store.commit('SET_LANGLIST', { ...res.data, zh: res.data.zh });
    //   setLocale({ ...res.data, zh: res.data.zh });
    // });
  } else {
    await setLocale(langList);
  }
  if (import.meta.env.VITE_USER_NODE_ENV === "production") {
    versionTood.isNewVersion();
  }
  if (token) {
    if (to.path === '/login') {
      // 使用返回值方式重定向
      NProgress.done()
      next('/home/index')
    } else {
      if (store.getters.roles.length === 0) {

        try {
          const params = { type: store.getters.type }
          const res = await api.default.user.getUserInfo(params)

          if (!res.data.user || !res.data.permissions?.length) {
            console.error('该用户有误！')
            NProgress.done()
            await store.dispatch('LogOut')
            location.reload()
            return
          }

          store.commit('SET_USERINFO', res.data.user)
          store.commit('SET_ROLES', res.data.roles)
          store.commit('SET_PERMISSIONS', res.data.permissions)

          const params1 = { type: store.getters.type }
          const accessRoutes = await store.dispatch('GenerateRoutes', params1)

          // 添加404路由
          accessRoutes.push({ path: '/:catchAll(.*)', redirect: '/home/index', hidden: true })
          // 动态添加路由 - Vue Router 4 方式
          accessRoutes.forEach(route => {
            console.log(route);

            router.addRoute(route)
          })

          NProgress.done()
          next({ ...to, replace: true })
        } catch (error) {
          console.error('用户信息获取失败:', error)
          await store.dispatch('LogInit')
          NProgress.done()
          next({ path: '/' })
        }
      } else {
        // 已有用户信息，直接放行
        NProgress.done()
        next()
      }
    }
  } else {

    if (whiteList.includes(to.path)) {
      // 在白名单中，直接放行
      NProgress.done()
      next()
    } else {
      NProgress.done()
      next('/login')
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})


router.onError((error) => {
  console.log("router onError", error);
  const pattern = /Loading chunk (\d)+ failed/g;
  const isChunkLoadFailed = error.message.match(pattern);
  // if (!router.history) return;
  const targetPath = router?.history?.pending.fullPath;
  if (isChunkLoadFailed && targetPath) {
    // router.replace(targetPath);
  }
});